<template>
  <div class="container">
    <div class="app-container">
      <div class="addRole">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column prop="name" label="角色" align="center" width="200">
          <!-- 自定义行内内容 -->
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.rowEdit.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.rowEdit.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.rowEdit.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="butEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnpermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <!-- 删除按钮 气泡框 -->
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delEdit(row)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height: 60px;" align="middle" justify="end">
        <!-- 绑定分页信息 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 放置弹层代码 点击新增角色 -->
    <el-dialog width="500px" titel="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="roleForm" :rules="rules" :model="roleForm" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" size="mini" style="width: 300px;" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述" size="mini">
          <el-input v-model="roleForm.description" size="mini" style="width: 300px;" type="textarea" :row="3" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限弹层 -->
    <el-dialog :visible.sync="showDialogpermission" title="分配权限">
      <!-- 设置node-key和当前选中的数据 -->
      <el-tree ref="permTree" check-strictly="false" node-key="id" :data="permissionDate" :props="{ label: 'name' }" :default-checked-keys="permIds" show-checkbox default-expand-all />
      <!-- 提交按钮 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="butPermissionOk">确定</el-button>
          <el-button size="mini" @click="showDialogpermission = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, eidtRole, delRole, getRoleDetail, assignPrem } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPerssionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      showDialog: false,
      // 分页数据
      pageParams: {
        page: 1, // 默认当前第一页1
        pagesize: 5, // 每页多少条
        total: 0 // 总共页数
      },
      // 表单数据
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      // 控制弹层显示 和接收权限数据2
      showDialogpermission: false,
      permissionDate: [],
      // 声明变量记录当前点击角色id和拥有的权限数据
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      // 将总数赋值
      this.pageParams.total = total
      // 给每一列数据添加一个编辑的属性 由于添加的动态属性不具备响应式 用this.$set(目标对象，属性名，初始值)
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'rowEdit', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页时，请求新数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList() // 再次请求数据更新页面组件
    },
    // 确定
    btnOk() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // 取消
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 行列编辑的方法
    btnEditRow(row) {
      row.isEdit = true
      row.rowEdit.name = row.name
      row.rowEdit.description = row.description
      row.rowEdit.state = row.state
    },
    // 编辑 确定按钮
    async butEditOk(row) {
      if (row.rowEdit.name && row.rowEdit.description) {
        await eidtRole({ ...row.rowEdit, id: row.id })
        this.$message.success('编辑角色成功')
        Object.assign(row, {
          ...row.rowEdit,
          isEdit: false
        })
      } else {
        this.$message.warning('角色名称或描述不能为空')
      }
    },
    async delEdit(row) {
      await delRole(row)
      this.$message.success('删除角色成功')
      // 删除的如果是这页的最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 分配权限数据转化为树形 控制弹层显示
    async btnpermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionDate = transListToTreeData(await getPerssionList(), 0)
      this.showDialogpermission = true
    },
    // 确定提交
    async butPermissionOk() {
      await assignPrem({
        id: this.currentRoleId,
        // 调用组件自定义方法 记录已经选中的数据做双向绑定
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showDialogpermission = false
    }
  }
}
</script>
<style scoped lang="scss">
.addRole {
  padding: 10px;
}
</style>
addRole,
